'use client'

import { useState } from 'react'
import { trpc } from '@/lib/trpc-provider'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Copy, RotateCcw, Palette } from 'lucide-react'
import { toast } from 'sonner'

type ColorFormat = 'hex' | 'rgb' | 'hsl' | 'hsv'

export default function ColorConverterPage() {
  const [inputColor, setInputColor] = useState('#ff0000')
  const [fromFormat, setFromFormat] = useState<ColorFormat>('hex')
  const [toFormat, setToFormat] = useState<ColorFormat>('rgb')
  const [results, setResults] = useState<{
    hex: string
    rgb: string
    hsl: string
    preview: { r: number, g: number, b: number } | null
  }>({ hex: '', rgb: '', hsl: '', preview: null })

  const convertColor = trpc.tools.convertColor.useMutation({
    onSuccess: (data) => {
      if (data.success && data.result && data.rgb) {
        // 转换为所有格式
        const rgb = data.rgb
        const hex = `#${rgb.r.toString(16).padStart(2, '0')}${rgb.g.toString(16).padStart(2, '0')}${rgb.b.toString(16).padStart(2, '0')}`
        const rgbStr = `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`
        
        // 计算HSL
        const r = rgb.r / 255
        const g = rgb.g / 255
        const b = rgb.b / 255
        const max = Math.max(r, g, b)
        const min = Math.min(r, g, b)
        let h = 0, s = 0, l = (max + min) / 2

        if (max !== min) {
          const d = max - min
          s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
          switch (max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break
            case g: h = (b - r) / d + 2; break
            case b: h = (r - g) / d + 4; break
          }
          h /= 6
        }

        const hslStr = `hsl(${Math.round(h * 360)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%)`
        
        setResults({
          hex,
          rgb: rgbStr,
          hsl: hslStr,
          preview: rgb
        })
      } else {
        toast.error(data.error || '颜色转换失败')
      }
    },
    onError: (error) => {
      toast.error(error.message || '颜色转换失败')
    }
  })

  const handleConvert = () => {
    if (!inputColor.trim()) {
      toast.error('请输入颜色值')
      return
    }

    convertColor.mutate({
      color: inputColor,
      fromFormat,
      toFormat: 'rgb' // 我们总是转换为RGB来获取所有格式
    })
  }

  const handleCopy = async (text: string, format: string) => {
    try {
      await navigator.clipboard.writeText(text)
      toast.success(`${format}值已复制到剪贴板`)
    } catch (error) {
      toast.error('复制失败')
    }
  }

  const handleClear = () => {
    setInputColor('')
    setResults({ hex: '', rgb: '', hsl: '', preview: null })
  }

  const handleQuickColor = (color: string) => {
    setInputColor(color)
    setFromFormat('hex')
  }

  const formatExamples = {
    hex: ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff'],
    rgb: ['rgb(255, 0, 0)', 'rgb(0, 255, 0)', 'rgb(0, 0, 255)', 'rgb(255, 255, 0)'],
    hsl: ['hsl(0, 100%, 50%)', 'hsl(120, 100%, 50%)', 'hsl(240, 100%, 50%)', 'hsl(60, 100%, 50%)'],
    hsv: ['hsv(0, 100%, 100%)', 'hsv(120, 100%, 100%)', 'hsv(240, 100%, 100%)']
  }

  const quickColors = [
    { name: '红色', value: '#ff0000' },
    { name: '绿色', value: '#00ff00' },
    { name: '蓝色', value: '#0000ff' },
    { name: '黄色', value: '#ffff00' },
    { name: '紫色', value: '#ff00ff' },
    { name: '青色', value: '#00ffff' },
    { name: '橙色', value: '#ffa500' },
    { name: '粉色', value: '#ffc0cb' },
    { name: '灰色', value: '#808080' },
    { name: '黑色', value: '#000000' },
    { name: '白色', value: '#ffffff' },
    { name: '棕色', value: '#a52a2a' }
  ]

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="max-w-4xl mx-auto">
        <div className="mb-8">
          <h1 className="text-3xl font-bold mb-2">颜色转换工具</h1>
          <p className="text-muted-foreground">
            在不同颜色格式之间进行转换：HEX、RGB、HSL等
          </p>
        </div>

        <div className="grid gap-6">
          {/* 输入区域 */}
          <Card>
            <CardHeader>
              <CardTitle>颜色输入</CardTitle>
              <CardDescription>
                输入要转换的颜色值
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div>
                    <Label htmlFor="color-input">颜色值</Label>
                    <Input
                      id="color-input"
                      value={inputColor}
                      onChange={(e) => setInputColor(e.target.value)}
                      placeholder="输入颜色值..."
                      className="font-mono"
                    />
                  </div>
                  <div>
                    <Label htmlFor="from-format">输入格式</Label>
                    <Select value={fromFormat} onValueChange={(value) => setFromFormat(value as ColorFormat)}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="hex">HEX (#ff0000)</SelectItem>
                        <SelectItem value="rgb">RGB (rgb(255,0,0))</SelectItem>
                        <SelectItem value="hsl">HSL (hsl(0,100%,50%))</SelectItem>
                        <SelectItem value="hsv" disabled>HSV (暂不支持)</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="flex items-end">
                    <Button
                      onClick={handleConvert}
                      disabled={convertColor.isPending}
                      className="w-full"
                    >
                      <Palette className="w-4 h-4 mr-2" />
                      转换颜色
                    </Button>
                  </div>
                </div>
                
                {/* 格式示例 */}
                <div>
                  <Label className="text-sm font-medium">格式示例：</Label>
                  <div className="mt-2 flex flex-wrap gap-2">
                    {formatExamples[fromFormat]?.map((example, index) => (
                      <button
                        key={index}
                        onClick={() => setInputColor(example)}
                        className="px-2 py-1 text-xs bg-muted hover:bg-muted/80 rounded font-mono transition-colors"
                      >
                        {example}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 快速颜色选择 */}
          <Card>
            <CardHeader>
              <CardTitle>快速颜色</CardTitle>
              <CardDescription>
                点击选择常用颜色
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-6 md:grid-cols-12 gap-2">
                {quickColors.map((color, index) => (
                  <button
                    key={index}
                    onClick={() => handleQuickColor(color.value)}
                    className="aspect-square rounded border-2 border-border hover:border-primary transition-colors relative group"
                    style={{ backgroundColor: color.value }}
                    title={`${color.name} (${color.value})`}
                  >
                    <span className="absolute inset-x-0 -bottom-6 text-xs text-center opacity-0 group-hover:opacity-100 transition-opacity">
                      {color.name}
                    </span>
                  </button>
                ))}
              </div>
            </CardContent>
          </Card>

          {/* 转换结果 */}
          {(results.hex || results.rgb || results.hsl) && (
            <Card>
              <CardHeader>
                <CardTitle>转换结果</CardTitle>
                <CardDescription>
                  所有格式的颜色值
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {/* 颜色预览 */}
                  {results.preview && (
                    <div className="flex items-center gap-4">
                      <div
                        className="w-20 h-20 rounded-lg border-2 border-border"
                        style={{ backgroundColor: results.hex }}
                      />
                      <div>
                        <h4 className="font-medium">颜色预览</h4>
                        <p className="text-sm text-muted-foreground">
                          RGB: {results.preview.r}, {results.preview.g}, {results.preview.b}
                        </p>
                      </div>
                    </div>
                  )}

                  {/* 格式结果 */}
                  <div className="grid gap-4">
                    {results.hex && (
                      <div className="flex items-center justify-between p-3 bg-muted rounded-lg">
                        <div>
                          <Label className="text-sm font-medium">HEX</Label>
                          <p className="font-mono text-sm">{results.hex}</p>
                        </div>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleCopy(results.hex, 'HEX')}
                        >
                          <Copy className="w-4 h-4" />
                        </Button>
                      </div>
                    )}
                    
                    {results.rgb && (
                      <div className="flex items-center justify-between p-3 bg-muted rounded-lg">
                        <div>
                          <Label className="text-sm font-medium">RGB</Label>
                          <p className="font-mono text-sm">{results.rgb}</p>
                        </div>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleCopy(results.rgb, 'RGB')}
                        >
                          <Copy className="w-4 h-4" />
                        </Button>
                      </div>
                    )}
                    
                    {results.hsl && (
                      <div className="flex items-center justify-between p-3 bg-muted rounded-lg">
                        <div>
                          <Label className="text-sm font-medium">HSL</Label>
                          <p className="font-mono text-sm">{results.hsl}</p>
                        </div>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleCopy(results.hsl, 'HSL')}
                        >
                          <Copy className="w-4 h-4" />
                        </Button>
                      </div>
                    )}
                  </div>

                  <div className="flex gap-2">
                    <Button variant="outline" onClick={handleClear}>
                      <RotateCcw className="w-4 h-4 mr-2" />
                      清空
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {/* 使用说明 */}
          <Card>
            <CardHeader>
              <CardTitle>使用说明</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4 text-sm">
                <div>
                  <h4 className="font-medium mb-2">支持的颜色格式：</h4>
                  <ul className="list-disc list-inside space-y-1 text-muted-foreground">
                    <li><strong>HEX</strong>: 十六进制格式，如 #ff0000 或 #f00</li>
                    <li><strong>RGB</strong>: 红绿蓝格式，如 rgb(255, 0, 0)</li>
                    <li><strong>HSL</strong>: 色相饱和度亮度格式，如 hsl(0, 100%, 50%)</li>
                  </ul>
                </div>
                <div>
                  <h4 className="font-medium mb-2">使用技巧：</h4>
                  <ul className="list-disc list-inside space-y-1 text-muted-foreground">
                    <li>点击快速颜色可以快速选择常用颜色</li>
                    <li>点击格式示例可以快速填入对应格式的示例</li>
                    <li>转换后可以复制任意格式的结果</li>
                    <li>支持3位和6位的HEX格式</li>
                  </ul>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}